import { StyleManager } from '../module/style_manager'
import {
  CustomElementStyleId,
  MessageType,
  MODULE_CONFIG,
  PROJECT_PREFIX,
} from '../types/constants'

export interface IMessageOptions {
  id?: string
  content: string
  type?: MessageType
  autoHide?: boolean
  duration?: number
}

export class MessageAlert {
  private static instance: MessageAlert
  // 样式标签 id
  private styleId: string = CustomElementStyleId.CustomMessage
  // 消息提示元素 id
  messageId: string = MODULE_CONFIG.COMPONENTS.messageAlert.id
  // 默认持续时间（毫秒）
  private defaultDuration: number = 5000

  constructor() {
    this.registerStyle(this.messageId)
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): MessageAlert {
    if (!MessageAlert.instance) {
      MessageAlert.instance = new MessageAlert()
    }
    return MessageAlert.instance
  }

  /**
   * 显示消息提示
   */
  showMessage(options: IMessageOptions): void {
    const { id, content, type = MessageType.INFO, autoHide = true, duration } = options
    const messageId = id || this.messageId
    let $message = $(`#${messageId}`)

    if (messageId !== this.messageId)
      this.removeMessage()

    if ($message && $message.length > 0) {
      $message.html(content).delay(500).show()
    }
    else {
      $message = $(`
      <div id="${messageId}" class="${type}">
        ${content}
      </div>
    `).appendTo('body')
    }

    if (autoHide) {
      // 自动隐藏（不影响其他指示器）
      setTimeout(() => $message.fadeOut(500), duration || this.defaultDuration)
    }
  }

  /**
   * 移除消息提示
   */
  removeMessage(): void {
    $(`#${this.messageId}`)?.remove()
  }

  /**
   * 注册样式
   */
  registerStyle(id: string): void {
    StyleManager.getInstance().registerStyle(this.styleId, this.styles(id), false, true)
  }

  /**
   * 样式
   */
  styles(id: string): string {
    return `
#${id} {
  position: fixed;
  bottom: 20px;
  left: 20px;
  background: var(--${PROJECT_PREFIX}-theme-loading-alert-bg) !important;
  color: var(--${PROJECT_PREFIX}-theme-loading-alert-text) !important;
  padding: 10px 15px;
  border-radius: 4px;
  z-index: 1000;
  font-size: 14px !important;
  
  &.${MessageType.ERROR} {
    color: var(--${PROJECT_PREFIX}-theme-danger-text) !important;
  }
  &.${MessageType.WARNING} {
    color: var(--${PROJECT_PREFIX}-theme-warning-text) !important;
  }
  &.${MessageType.SUCCESS} {
    color: var(--${PROJECT_PREFIX}-theme-success-text) !important;
  }
  &.${MessageType.INFO} {
    color: var(--${PROJECT_PREFIX}-theme-info-text) !important;
  }
  &.${MessageType.LOADING} {
    color: var(--${PROJECT_PREFIX}-theme-info-text) !important;
  }
}
`
  }
}
